
import 'dart:async';

import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:test01/okhttp_test/page/indexlogin/usernick_page.dart';
import 'package:test01/okhttp_test/page/pages/tabbarview_test.dart';
import 'package:test01/okhttp_test/page/personalhomepage/dynamic/my_dynamic_page.dart';
import 'package:test01/okhttp_test/pojo/login_request_pojo.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

/*
*
* 登录界面----------手机验证码
*
*
* */


class VerificationCodePage extends StatefulWidget {
  const VerificationCodePage({Key key,this.phoneCode}) : super(key: key);
  final String phoneCode;

  @override
  VerificationCodePageState createState() => VerificationCodePageState();
}

class VerificationCodePageState extends State<VerificationCodePage> {
  ///输入框控制器
  TextEditingController controller;
  ///判断是否可以验证
  bool isShowVerification=false;
  ///判断是否显示登录
  bool isShowSend=false;

  ///获取界面验证码
  String codeText;

  ///倒计时
  Timer _timer;
  int _start = 60;
  ///倒计时是否结束
  bool isShowTimer=true;


  ///初始化
  @override
  void initState() {
    isShowTimer=false;
    startTimer();
    setState(() {

    });
    super.initState();
  }



  void startTimer() {
    const oneSec = const Duration(seconds: 1);//间隔1秒
    _timer = new Timer.periodic(oneSec, //每秒调用一次
          (Timer timer) => setState(
            () {
          if (_start <= 1) { //如果小于1则停止倒计时
            timer.cancel();
            isShowTimer=true;
          } else {
            _start = _start - 1;//自减一
            isShowTimer=false;
          }
        },
      ),
    );
  }

  ///获取登录token
  void logintoken(String code) async{
    LoginRequst loginRequst=LoginRequst(authorization:"Basic dXNlckFwcDpBaW15Rml0bmVzcw==",grant_type:"sms",username:widget.phoneCode,code:code);
    LoginRespons loginRespons=await getinittokens(loginRequst, "/uaa/oauth/login");
    if(loginRespons!=null){
      isShowSend=false;
      Fluttertoast.showToast(msg:"登录成功！",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.BOTTOM,
          textColor: Colors.white,
          fontSize: 14.0
      );

      if(loginRespons.isPerfect==1){
        ///界面跳转---登录成功

        Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) {
          return TabBarViewPage();
        }), (route) => false);



        // Navigator.pop(context, MaterialPageRoute(builder: (context) {
        //   return TabBarViewPage();
        // }));



        tokens="${loginRespons.token_type} ${loginRespons.access_token}";
        refreshtokens="${loginRespons.refresh_token}";
      }else{
        ///界面跳转
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return UserNickName();
        }));
        tokens="${loginRespons.token_type} ${loginRespons.access_token}";
        refreshtokens="${loginRespons.refresh_token}";
      }

    }


    else{
      isShowSend=false;
      Fluttertoast.showToast(msg:"验证码错误！",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.BOTTOM,
          textColor: Colors.white,
          fontSize: 14.0
      );
    }
  }



  /// 手机号分割 15944443333 -> 155 4444 3333
  String splitPhoneNumber() {
    Pattern regex = RegExp(r'(1\w{2})(\w{4})(\w{4})');
    return widget.phoneCode.replaceAllMapped(
        regex, (match) => '${match[1]}****${match[3]}');
  }

  @override
  void dispose() {
    // TODO: implement dispose
    if(_timer!=null){
      _timer.cancel();
    }
    super.dispose();
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            leading:
            IconButton(icon: Icon(Icons.clear,color: Colors.black),onPressed: (){
              ///界面返回
              Navigator.of(context).pop();
              print("返回");
            },),
            backgroundColor: Colors.white,
            elevation: 0,
            brightness: Brightness.light //light是黑字，dark是白字

        ),


        body: Container(
            color: Colors.white,
            ///手机屏宽
            width: MediaQuery.of(context).size.width,
            child:
            Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.fromLTRB(41, 42.5, 0, 0),
                    child: Text(
                      "输入验证码",
                      style: TextStyle(fontSize: 23,color: Color.fromRGBO(17, 17, 17, 1)),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(41, 9, 0, 0),
                    child: Text(
                      "短信验证码已发送至 +86 ${splitPhoneNumber()}",
                      style: TextStyle(
                          fontSize: 14,
                          color: Color.fromRGBO(153, 153, 153, 1)
                      ),
                    ),
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width-82 ,
                    margin: EdgeInsets.fromLTRB(41, 38, 0, 0),
                    child:
                    TextField(
                      autofocus: false,
                      controller: controller,
                      maxLength: 4,
                      decoration:
                      InputDecoration(
                        counterText:"",
                        suffixIcon:
                        ///获取验证码倒计时
                        GestureDetector(
                          onTap:(){
                            startTimer();
                            _start=60;
                          },
                          child:Container(
                            padding: EdgeInsets.only(left: 13,top: 13,bottom: 13),
                            child:Container(
                              alignment: Alignment.center,
                              width: 70,
                              decoration: BoxDecoration(
                                color: Color.fromRGBO(17, 17, 17, 0.06),
                                border: isShowTimer?Border.all(width: 1,color:Color.fromRGBO(17, 17, 17, 1)):Border.all(width: 1,color: Color.fromRGBO(204, 204, 204, 1)),
                                borderRadius:
                                BorderRadius.all(Radius.circular(3.0)),
                              ),
                              child:isShowTimer? Text("重新获取",style: TextStyle(fontSize: 13,color: Color.fromRGBO(17, 17, 17, 1)),):
                              Text("${_start}s",style: TextStyle(fontSize: 13,color: Color.fromRGBO(204, 204, 204, 1))),
                            ),
                          ),

                        ),
                        hintText: "输入验证码",
                        hintStyle: TextStyle(color: Color.fromRGBO(153, 153, 153, 1),fontSize: 16),
                        hintMaxLines: 1,
                        ///获取焦点
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey.withOpacity(0.2),
                            )),
                        ///默认状态下
                        enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey.withOpacity(0.2),
                            )),
                      ),
                      ///获取文本框数据
                      onChanged: (value){
                        if(value.length!=4){
                          isShowVerification=false;
                        }else{
                          codeText=value;
                          isShowVerification=true;
                        }
                        setState(() {

                        });
                      },
                      ///设置键盘格式
                      keyboardType: TextInputType.phone, //手机号
                    ),
                  ),

                  GestureDetector(
                    ///判断按钮状态
                    onTap: () {
                       logintoken(codeText);
                    },
                    child:Container(
                      height: 44,
                      width: MediaQuery.of(context).size.width-81,
                      margin: EdgeInsets.only(left: 41,top: 32),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: isShowVerification?Color.fromRGBO(17, 17, 17, 1):Color.fromRGBO(17, 17, 17, 0.06),
                        borderRadius:
                        BorderRadius.all(Radius.circular(3.0)),
                      ),
                      child:isShowSend?
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            width: 17,
                            height: 17,
                            child:CircularProgressIndicator(
                              color: Color.fromRGBO(255, 255, 255, 1),
                              strokeWidth: 2,
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 8.5),
                            child: Text("验证",style: TextStyle(fontSize: 16,color: Color.fromRGBO(255, 255, 255, 1)),),
                          ),
                        ],
                      ):
                      Text("验证",style: TextStyle(fontSize: 16,color: isShowVerification?Color.fromRGBO(255, 255, 255, 1):Color.fromRGBO(153, 153, 153, 1)),),
                    ),
                  ),
                ]
            )
        )
    );
  }
}









